package com.aiyi.education.admin.service.impl;


import cn.hutool.crypto.digest.BCrypt;
import com.aiyi.education.admin.service.IKsAdminService;
import com.aiyi.education.entity.KsUserWithBLOBs;
import com.aiyi.education.entity.admin.KsAdmin;
import com.aiyi.education.mapper.admin.KsAdminMapper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.education.base.Constant;
import com.education.base.ErrorReturnConstant;
import com.education.base.PublicResultConstant;
import com.education.exception.BusinessException;
import com.education.util.ComUtil;
import com.education.util.JWTUtil;
import com.education.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author renyong
 * @email sxgyry@163.com
 * @date
 */
@Service
public class KsAdminServiceImpl extends ServiceImpl<KsAdminMapper, KsAdmin> implements IKsAdminService {

    @Autowired
    KsAdminMapper ksAdminMapper;

    @Override
    public Map<String, Object> checkLoginAccountAndPasswd(JSONObject requestJson) throws Exception {
        //由于 @ValidationParam注解已经验证过mobile和passWord参数，所以可以直接get使用没毛病。
        String userAccount = requestJson.getString("userAccount");
        //手机号格式验证
        /*if(!StringUtil.checkMobileNumber(mobile)){
            throw new BusinessException(PublicResultConstant.MOBILE_ERROR);
        }*/
        if (StringUtils.isEmpty(userAccount)||StringUtils.isEmpty(requestJson.getString("password"))) {
            throw new BusinessException(ErrorReturnConstant.ACCOUNT_OR_PASSWORD_CANNOT_BE_EMPTY);
        }

        KsAdmin user = this.userAccountMatching(requestJson);
        if (ComUtil.isEmpty(user) || !BCrypt.checkpw(requestJson.getString("password"), user.getPassword())) {
            throw new BusinessException(PublicResultConstant.INVALID_USERNAME_PASSWORD);
        }
        //测试websocket用户登录给管理员发送消息的例子  前端代码参考父目录下WebSocketDemo.html
//        noticeService.insertByThemeNo("themeNo-cwr3fsxf233edasdfcf2s3","13888888888");
//        MyWebSocketService.sendMessageTo(JSONObject.toJSONString(user),"13888888888");

        return this.getLoginUserAndMenuInfo(user);
    }

    @Override
    public KsAdmin checkAndRegisterUser(JSONObject requestJson) throws Exception {
        //可直接转为java对象,简化操作,不用再set一个个属性
        KsAdmin userRegister = requestJson.toJavaObject(KsAdmin.class);
        if(!StringUtils.isEmpty(requestJson.getString("userAccount"))){
            throw new BusinessException(PublicResultConstant.INVALID_USERNAME_PASSWORD);
        }
        if (!userRegister.getPassword().equals(requestJson.getString("rePassword"))) {
            throw new BusinessException(PublicResultConstant.INVALID_RE_PASSWORD);
        }
        /*List<SmsVerify> smsVerifies = smsVerifyService.getByMobileAndCaptchaAndType(userRegister.getMobile(),
                requestJson.getString("captcha"), SmsSendUtil.SMSType.getType(SmsSendUtil.SMSType.REG.name()));
        if(ComUtil.isEmpty(smsVerifies)){
            throw new BusinessException(PublicResultConstant.VERIFY_PARAM_ERROR);
        }
        //验证码是否过期
        if(SmsSendUtil.isCaptchaPassTime(smsVerifies.get(0).getCreateTime())){
            throw new BusinessException(PublicResultConstant.VERIFY_PARAM_PASS);
        }*/
        userRegister.setPassword(BCrypt.hashpw(requestJson.getString("password"), BCrypt.gensalt()));
        //默认注册普通用户
        return this.register(userRegister, Constant.UserLoginType.USER);
    }


    @Override
    public Map<String, Object> getLoginUserAndMenuInfo(KsAdmin user) {
        Map<String, Object> result = new HashMap<>();
        // BaseUserToRole baseUserToRole = baseUserToRoleService.selectByUserNo(user.getUserNo());
        user.setToken(JWTUtil.sign(user.getId().toString(), user.getPassword(),Constant.UserLoginType.ADMIN));
        //更新最后登录时间
        KsAdmin updateUser = new KsAdmin();
        updateUser.setId(user.getId());
        updateUser.setLastLoginTime(new Date());
        this.updateById(updateUser);
        //过滤字段
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
        filter.getExcludes().add("password");
        filter.getExcludes().add("rndPassword");
        filter.getExcludes().add("loginTimes");
        filter.getExcludes().add("checkNum");
        String resultJson = JSONObject.toJSONString(user,filter);
        user = JSON.parseObject(resultJson,KsAdmin.class);
        result.put("user",user);
        /*List<BaseMenu> buttonList = new ArrayList<BaseMenu>();
        List<BaseMenu> retMenuList = new ArrayList<BaseMenu>();*/

        //根据角色主键查询启用的菜单权限
        // List<BaseMenu> menuList = baseMenuService.findBaseMenuByRoleCode(baseUserToRole.getRoleCode());
       /*
        List<BaseMenu> retMenuList = baseMenuService.treeBaseMenuList(Constant.ROOT_MENU, menuList);
        for (BaseMenu buttonMenu : menuList) {
            if(buttonMenu.getMenuType() == Constant.TYPE_BUTTON){
                buttonList.add(buttonMenu);
            }
        }
        */
        /*result.put("menuList",retMenuList);
        result.put("buttonList",buttonList);*/
        return result;
    }

    @Override
    public KsAdmin getUserByUserNo(String userNo) {
        return ksAdminMapper.selectByPrimaryKey(Integer.parseInt(userNo));
    }

    private KsAdmin register(KsAdmin user, String  roleCode) throws Exception {
        JSONObject requestJson = JSON.parseObject(JSON.toJSONString(user));
        KsAdmin exist = this.userAccountMatching(requestJson);
        if (exist==null){
            //user.setUserId(GenerationSequenceUtil.generateUUID("user"));
            user.setAddDate(new Date());
            boolean result = this.save(user);
        /*if (result) {
            BaseUserToRole userToRole  = BaseUserToRole.builder().userNo(user.getUserNo()).roleCode(roleCode).build();
            baseUserToRoleService.insert(userToRole);
        }*/
        }else{
         throw new BusinessException(ErrorReturnConstant.USER_ALREADY_EXISTS);
        }
        return user;
    }

    private KsAdmin userAccountMatching(JSONObject requestJson){
        QueryWrapper wrapper = new QueryWrapper();
        StringBuffer existsSql = new StringBuffer("select id from ks_admin where ");
        if (StringUtils.isNotEmpty(requestJson.getString("userAccount"))){
            existsSql.append("id = \'"+ requestJson.getString("userAccount")+"\'");
            existsSql.append(" or user_name = \'"+requestJson.getString("userAccount")+"\'");
        }
        wrapper.exists(existsSql.toString());
        KsAdmin user = this.getOne(wrapper);
        return user;
    }
}
